package com.agent.payment.service;

import com.agent.payment.config.PaymentGatewayConfig;
import com.agent.payment.entity.PaymentOrder;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * Asiabill支付服务
 * @author Jeff_Wan
 * @description 处理Asiabill支付网关的集成逻辑
 */
@Service
@RequiredArgsConstructor
public class AsiabillService {
    private final PaymentGatewayConfig paymentGatewayConfig;
    
    /**
     * 创建Asiabill支付请求
     * @param order 支付订单
     * @return 支付请求参数
     */
    public Map<String, String> createPaymentRequest(PaymentOrder order) {
        Map<String, String> params = new HashMap<>();
        
        // 从配置中获取参数
        PaymentGatewayConfig.AsiabillConfig config = paymentGatewayConfig.getAsiabill();
        
        // 基本参数
        params.put("merNo", config.getMerchantNo());
        params.put("gatewayNo", config.getGatewayNo());
        params.put("orderNo", order.getOrderNumber());
        params.put("orderCurrency", order.getCurrency());
        params.put("orderAmount", order.getAmount().toString());
        params.put("returnUrl", config.getReturnUrl());
        params.put("notifyUrl", config.getNotifyUrl());
        
        // 生成签名
        String signData = buildSignData(params);
        String sign = HmacUtils.hmacSha256Hex(config.getSignKey(), signData);
        params.put("signInfo", sign);
        
        return params;
    }
    
    /**
     * 验证Asiabill回调签名
     * @param callbackData 回调数据
     * @param signature 签名
     * @return 是否验证通过
     */
    public boolean verifyCallback(String callbackData, String signature) {
        String signKey = paymentGatewayConfig.getAsiabill().getSignKey();
        String expectedSign = HmacUtils.hmacSha256Hex(signKey, callbackData);
        return expectedSign.equals(signature);
    }
    
    /**
     * 从回调数据中解析订单号
     * @param callbackData 回调数据
     * @return 订单号
     */
    public String parseOrderNumber(String callbackData) {
        // 解析回调数据获取订单号
        int startIndex = callbackData.indexOf("orderNo=") + 8;
        int endIndex = callbackData.indexOf("&", startIndex);
        if (endIndex == -1) endIndex = callbackData.length();
        return callbackData.substring(startIndex, endIndex);
    }
    
    /**
     * 构建签名字符串
     * @param params 请求参数
     * @return 签名字符串
     */
    private String buildSignData(Map<String, String> params) {
        return params.get("merNo") + "|" +
               params.get("gatewayNo") + "|" +
               params.get("orderNo") + "|" +
               params.get("orderAmount") + "|" +
               params.get("orderCurrency");
    }
}